from tortoise import fields, models


class SystemConfigModel(models.Model):
    """系统配置模型"""
    
    id = fields.IntField(pk=True)
    key = fields.CharField(max_length=100, unique=True, description="配置键")
    value = fields.TextField(description="配置值")
    description = fields.CharField(max_length=255, null=True, description="配置描述")
    type = fields.CharField(max_length=20, default="string", description="配置类型：string, int, float, bool, json")
    is_system = fields.BooleanField(default=False, description="是否系统配置")
    is_public = fields.BooleanField(default=True, description="是否公开配置")
    remark = fields.TextField(null=True, description="备注")
    created_at = fields.DatetimeField(auto_now_add=True, description="创建时间")
    updated_at = fields.DatetimeField(auto_now=True, description="更新时间")

    class Meta:
        table = "system_configs"
        table_description = "系统配置表"

    def __str__(self):
        return f"{self.key}: {self.value}"

    @classmethod
    async def get_config(cls, key: str, default=None):
        """获取配置值"""
        config = await cls.filter(key=key).first()
        if not config:
            return default
        return config.value

    @classmethod
    async def set_config(cls, key: str, value: str, description: str = None, config_type: str = "string"):
        """设置配置值"""
        config, created = await cls.get_or_create(
            key=key,
            defaults={
                "value": value,
                "description": description,
                "type": config_type
            }
        )
        if not created:
            config.value = value
            config.description = description
            config.type = config_type
            await config.save()
        return config

    @classmethod
    async def get_public_configs(cls):
        """获取公开配置"""
        return await cls.filter(is_public=True).order_by('key')

    @classmethod
    async def get_system_configs(cls):
        """获取系统配置"""
        return await cls.filter(is_system=True).order_by('key') 